package com.qf.shiro;

import com.alibaba.druid.util.StringUtils;
import com.hazelcast.util.StringUtil;
import com.qf.pojo.DtsAdmin;
import com.qf.service.AdminService;
import com.qf.service.PermissionService;
import com.qf.service.RoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.DataOutput;
import java.util.List;
import java.util.Set;


public class AdminAuthorizingRealm extends AuthorizingRealm {


    @Autowired
    AdminService adminService;

    @Autowired
    RoleService roleService;

    @Autowired
    PermissionService permissionService;



    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权
        if(principalCollection==null){
            throw new AuthenticationException("用户名不能为空");

        }
        DtsAdmin admin = (DtsAdmin) getAvailablePrincipal(principalCollection);

        Integer[] roleIds = admin.getRoleIds();

        Set<String> roles = roleService.queryByIds(roleIds);

        Set<String> permissions = permissionService.queryByIds(roleIds);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);

        return info;

    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //认证
        String username = token.getUsername();
        String password = new String(token.getPassword());

        if(StringUtils.isEmpty(username)){
            throw new AccountException("用户名不能为空");
        }
        if(StringUtils.isEmpty(password)){
            throw new AccountException("密码不能空");
        }
        List<DtsAdmin> list = adminService.findAdmin(username);

        System.out.println(list);

        Assert.state(list.size()<2,"同一个账户存在两个账户");
        if(list.size()==0){
            throw new UnknownAccountException("找不到账户");
        }
        DtsAdmin admin = list.get(0);

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        if(!encoder.matches(password,admin.getPassword())){
            throw new UnknownAccountException("找不到用户");

        }
        AuthenticationInfo info = new SimpleAuthenticationInfo(admin, password, username);

        return info;
    }


















}
